<template>
  <div class="header-search">
    <span @click="enterSearchMode">
      <a-icon type="search" class="search-icon" />
      <span class="text">菜单搜索</span>
    </span>
    <a-select
      show-search
      placeholder="请选择"
      option-filter-prop="children"
      :filter-option="true"
      @change="handleChange"
      ref="input"
      :class="['search-input', searchMode ? 'enter' : 'leave']"
      @blur="leaveSearchMode"
      @focus="handleFocus()"
      v-model="selectedMenu"
      allowClear
    >
      <a-select-option
        v-for="item in newMenuData"
        :key="item.id"
        @click="handleClick(item)"
      >
        {{ item.text }}
      </a-select-option>
    </a-select>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "HeaderSearch",
  data() {
    return {
      dataSource: [],
      searchMode: false,
      data: [],
      newMenuData: [],
      selectedMenu: null,
    };
  },
  created() {
    this.getMenuData();
  },
  computed: {
    ...mapState("setting", ["menuData"]),
  },
  methods: {
    handleFocus() {},
    getMenuData() {
      this.filterMenuData(this.menuData);
      this.newMenuData = this.data;
    },
    enterSearchMode() {
      this.selectedMenu = undefined;
      this.searchMode = true;
      this.$emit("active", true);
      setTimeout(() => {
        this.$refs.input.focus();
      }, 300);
    },
    leaveSearchMode() {
      this.searchMode = false;
      setTimeout(() => {
        this.$refs.input.blur();
        this.$emit("active", false);
      }, 300);
    },
    handleChange() {},
    handleClick(item) {
      if ("urlNewWindows" === item.menuType) {
        window.open(item.path);
      } else {
        this.$router.push(item.path);
      }
      setTimeout(() => this.$refs.input.blur(), 300);
    },
    filterMenuData(data) {
      data.forEach((item) => {
        if (item.children) {
          this.filterMenuData(item.children);
        } else {
          if (item.id) {
            this.data.push(item);
          }
        }
      });
    },
  },
};
</script>

<style lang="less">
.header-search {
  .search-icon {
    font-size: 16px;
    cursor: pointer;
    color: #1890ff;
  }
  .text {
    margin: 0 6px;
    font-size: 14px;
    color: #666666;
  }
  .search-input {
    border: 0;
    border-bottom: 1px solid @border-color-split;
    transition: width 0.3s ease-in-out;
    input {
      border: 0;
      box-shadow: 0 0 0 0;
    }
    &.leave {
      width: 0px;
      input {
        display: none;
      }
      .ant-select-selection {
        display: none;
        border: none;
      }
    }
    &.enter {
      width: 160px;
      input:focus {
        box-shadow: 0 0 0 0;
        border: none;
      }
      .ant-select-selection {
        border: none;
        box-shadow: none;
      }
    }
  }
}
</style>
